package com.hontech.bv.conn.usb

import android.content.Context
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import com.felhr.deviceids.CH34xIds
import com.felhr.deviceids.CP210xIds
import com.felhr.deviceids.FTDISioIds
import com.felhr.deviceids.PL2303Ids
import com.felhr.usbserial.UsbSerialDevice
import com.hontech.bv.app.AppContext
import com.hontech.bv.conn.SerialPort
import java.io.IOException

object UsbSerialPortMod {

    private fun isSupported(device: UsbDevice): Boolean {
        return CP210xIds.isDeviceSupported(device.vendorId, device.productId) ||
                FTDISioIds.isDeviceSupported(device) ||
                PL2303Ids.isDeviceSupported(device.vendorId, device.productId) ||
                CH34xIds.isDeviceSupported(device.vendorId, device.productId)
    }

    suspend fun open(): SerialPort {
        val usb = AppContext.getSystemService(Context.USB_SERVICE) as UsbManager
        val usbList = usb.deviceList.values
        for (device in usbList) {

            val flag = isSupported(device)
            if (!flag) {
                continue
            }
            val conn = openUsb(usb, device)
            if (FTDISioIds.isDeviceSupported(device)) {
                return FtdiSerialDevice(device, conn)
            }
            val port = UsbSerialDevice.createUsbSerialDevice(device, conn)
            return UsbSerialPort(port)
        }
        throw IOException("没有符合要求的USB设备插入")
    }


}

